package codeOfChapter04;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import homework04.Entity2;

public class TableInfo {
	private String tableName;
	private Class<?> clazz;
	private boolean needPersist = false;
	private Map<String, ColumnInfo> columns = new HashMap<String, ColumnInfo>();

	public static TableInfo parse(Class<?> clazz) {
		TableInfo table = new TableInfo();
		table.clazz = clazz;
		table.setTableName(table.clazz.getSimpleName());
		Annotation[] annotations = table.clazz.getAnnotations();
		for (Annotation annotation : annotations) {
			if (annotation.annotationType().equals(Entity2.class)) {
				table.needPersist = true;
				Entity2 entity = (Entity2) annotation;
				if (!entity.value().equals("")) {
					table.tableName = entity.value();
				}
				break;
			}
		}
		if (table.needPersist) {
			Field[] fields = table.clazz.getDeclaredFields();
			for (Field field : fields) {
				ColumnInfo column = new ColumnInfo();
				column = column.parse(field);
				if (column != null) {
					table.columns.put(field.getName(), column);
				}
			}
			return table;
		} else {
			return null;
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("\n" + "CREATE TABLE" + this.tableName + " " + "(");
		for (ColumnInfo column : this.columns.values()) {
			sb.append("\n" + "\t" + column.toString());
		}
		sb.append("\n" + ");");
		return sb.toString();

	}

	public String getTableName() {
		return tableName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
}
